package com.example.myapplication.fragments.fragmentsadapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.BR;
import com.example.myapplication.R;
import com.example.myapplication.fragments.fragmentsmodel.Missing;
import com.example.myapplication.fragments.fragmentsviewmodel.BindingViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
* recyclerview适配器类
*/
public class HomeRecyclerAdapter extends RecyclerView.Adapter<BindingViewHolder> {
    private LayoutInflater layoutInflater;
    private OnItemClickListener mListener; //item的点击监听器
    private List<Missing> list;

    public interface OnItemClickListener {
        void onItemClickListener(Missing missing);
    }

    public HomeRecyclerAdapter(Context context) {
        this.layoutInflater = LayoutInflater.from(context);
        this.list = new ArrayList<>();
    }

    @NonNull
    @Override
    public BindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewDataBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.item_home_fragment,parent,false);
        return new BindingViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull BindingViewHolder holder, int position) {
        final Missing item = list.get(position);
        ViewDataBinding binding = holder.getBinding();
        binding.setVariable(BR.item,item);
        binding.executePendingBindings();
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onItemClickListener(item);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }

    public void addAll(List<Missing> missings) {
        list.addAll(missings);
    }

    Random random = new Random(System.currentTimeMillis());

    public void add(Missing missing) {
        int position = random.nextInt(list.size()+1);
        list.add(position,missing);
        notifyItemInserted(list.size());
    }

    public void remove() {
        if (list.size() == 0) {
            return;
        }
        int position = random.nextInt(list.size());
        list.remove(position);
        notifyItemRemoved(position);
    }
}
